import { defineStore } from 'pinia';
import {
    setTokenLocal,
    setUserLocal,
    getUserLocal,
    getTokenLocal,
    removeTokenLocal,
    removeUserLocal
} from "@/utils/auth.js"

export const useUserStore = defineStore('user', {
    // 状态：定义 Store 中的数据
    state: () => {
        return {
            user: getUserLocal(), //从本地初始用户数据
            token: getTokenLocal(), //从本地初始Token
        }
    },

    // 获取器：类似于计算属性，用于获取状态的派生值
    getters: {
        theUser: (state) => state.user,
        theToken: (state) => state.token,
    },

    // 动作：用于修改状态的方法
    actions: {
        setUser(user) {
            this.user = user
            setUserLocal(user)
        },

        setToken(token) {
            this.token = token
            setTokenLocal(token)
        },

        removeUser() {
            this.user = null
            removeUserLocal()
        },

        removeToken() {
            this.token = null
            removeTokenLocal()
        },

        logout() {
            this.removeUser()
            this.removeToken()
        }
    },

});